/* 等级调整
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\CustomerManage\RightsAndInterests\component\LevelChangeDrawer.tsx
 * @Date: 2021-12-09 16:11:21
 * @LastEditTime: 2021-12-09 16:39:56
 */
import React, { createRef } from 'react'
import { http, IUdFormItem, UdForm, validators } from '@/lib'
import UdUploader from '@/components/UdUploader/Uploader'
import { Input, Select, InputNumber, message } from 'antd'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import apis from '@/apis/CustomerManage'
import toDoApis from '@/apis/TodoList'
import './approve.scss'
import QuotaApprove from '@/components/getQuotaApprove'

const { TextArea } = Input
const { Option } = Select
interface IProps {
  record: any
}
interface IState {
  recordDetail: any
  workFlowList: any[]
  checkPerson: any[]
  loading: boolean
  RightsRegisterDict: any[]
}
export default class LevelChangeDrawer extends React.Component<IProps, IState> {
  private labelCol: any = { span: 4 }
  private form: WrappedFormUtils
  public cRef = createRef<any>()
  private record = { ...this.props.record }
  state: IState = {
    recordDetail: {},
    workFlowList: [],
    checkPerson: [],
    loading: false,
    RightsRegisterDict: [],
  }

  componentDidMount() {
    this.init()
  }

  private onOk = e => {
    this.form.validateFields((err, values) => {
      if (!err) {
        // if (this.state.checkPerson.length === 0) {
        //   message.warn('请选择审批人')
        //   return false
        // }
        e.drawerBtnLoading()
        let params: Record<string, any> = { ...this.props.record, ...values }
        if (params.enjoyRightsLabelInValue && Array.isArray(params.enjoyRightsLabelInValue)) {
          let enjoyRightsCode:any[] = []
          let enjoyRightsStr:any[] = []
          for (let item of params.enjoyRightsLabelInValue) {
            enjoyRightsCode.push(item.key)
            enjoyRightsStr.push(item.label)
          }
          params.enjoyRightsCode = enjoyRightsCode.join(',')
          params.enjoyRightsStr = enjoyRightsStr.join(',')
        }
        // params['workflowReqVos'] = {
        //   name: 'candidateUsers',
        //   userId: [this.state.checkPerson[0].id],
        // }
        http
          .put(apis.updateRightsDetail, params)
          .then(() => {
            message.success('操作成功')
            e.close()
          })
          .catch(() => {
            e.drawerBtnLoadingHide()
          })
      } else {
        console.log(err)
      }
    })
  }

  //获取审批角色
  private getWorkFlow = (brandCode: number | string) => {
    return http.get(toDoApis.getRightsAndInterestsAdjustNextApprove, { params: { brandCode } })
  }

  //选择审批人
  private handShowQuotaApprove(index) {
    this.cRef.current.handelCeck(index)
  }

  private handGetPerson(value) {
    this.setState({ checkPerson: value })
  }

  private getDataDetail = (id: number | string) => {
    return http.get(apis.getRightsdetail, { params: { id } })
  }

  private getRightsRegisterDict = () => {
    return http.get(apis.getRightsRegisterDict)
  }

  private init = () => {
    const { id, brandCode } = this.record
    this.setState({ loading: true })
    Promise.allSettled([this.getDataDetail(id), this.getRightsRegisterDict()])
      //Promise.allSettled([this.getWorkFlow(brandCode), this.getDataDetail(id)])
      .then((res: any) => {
        // let record = res[1]?.value?.data || {}
        // record.enjoyRightsStr = record?.enjoyRightsStr && record.enjoyRightsStr.split(',')
        // this.setState({ workFlowList: res[0]?.value?.data || {}, recordDetail: res[1]?.value?.data || {} })
        let recordDetail = res[0]?.value?.data || {}

        let RightsRegisterDict = res[1]?.value?.data || []
        const enjoyRightsLabelInValue = []
        const enjoyRightsCode = recordDetail?.enjoyRightsCode?.split(',') || []
        for (let code of enjoyRightsCode) {
          let label = RightsRegisterDict.find(item => {
            return item.code === code
          })?.name
          enjoyRightsLabelInValue.push({ key: code, label })
        }
        recordDetail['enjoyRightsLabelInValue'] = enjoyRightsLabelInValue
        this.setState({ recordDetail, RightsRegisterDict })
      })
      .finally(() => {
        this.setState({ loading: false })
      })
  }

  render() {
    let items: IUdFormItem[] = [
      { label: '品牌公司', id: 'brandName', render: () => <Input readOnly /> },
      { label: '评级年度', id: 'appraiseYear', render: () => <Input readOnly /> },
      { label: '客户编码', id: 'customerCode', render: () => <Input readOnly /> },
      { label: '客户名称', id: 'customerName', render: () => <Input readOnly /> },
      { label: '原有等级', id: 'appraiseGrade', render: () => <Input readOnly /> },
      {
        label: '调整等级',
        id: 'originalAppraiseGrade',
        rules: [validators.required],
        render: () => (
          <Select>
            <Option value="VIP">VIP</Option>
            <Option value="A">A级</Option>
            <Option value="B">B级</Option>
            <Option value="C">C级</Option>
          </Select>
        ),
      },
      {
        label: '权益项目',
        rules: [validators.required],
        id: 'enjoyRightsLabelInValue',
        render: () => (
          <Select mode="multiple" labelInValue>
            {this.state.RightsRegisterDict.map(({ code, name }) => (
              <Option value={code} key={code}>
                {name}
              </Option>
            ))}
          </Select>
        ),
      },
      // { label: '原有排名', id: 'ranking', render: () => <Input readOnly /> },
      // {
      //   label: '调整排名',
      //   id: 'originalRanking',
      //   rules: [validators.required, validators.number],
      //   render: () => <InputNumber style={{ width: '100%' }} min={1} precision={0} />,
      // },
      { label: '备注信息', id: 'remarks', render: <TextArea rows={3} maxLength={200} /> },
      {
        label: '附件',
        id: 'quotaApplyDetailFileRespVoList',
        render: <UdUploader form={this.form} extra="支持扩展名：.jpg .png .xls .doc" />,
      },
    ]
    return (
      <>
        <UdForm
          labelCol={this.labelCol}
          getForm={form => (this.form = form)}
          items={items}
          values={this.state.recordDetail}
        />
        {/* <h4>审批流程</h4>
        <div className="approve-wrap">
          <div className="node-name-wrap">
            <div className="approve-title">节点名称：</div>
            <span className="circle-point"></span>
            <div>{this.state.workFlowList[0]?.nodeName || '暂无'}</div>
          </div>
          <div className="person-name-wrap">
            <div className="approve-title">审批人:</div>
            <div
              className={this.state.checkPerson[0]?.realName ? 'add-plus-name' : 'add-plus'}
              onClick={() => {
                this.handShowQuotaApprove(0)
              }}
            >
              {this.state.checkPerson[0]?.realName || '+'}
            </div>
          </div>
        </div>
        <QuotaApprove
          handCilck={this.handGetPerson.bind(this)}
          cRef={this.cRef}
          ids={this.state.workFlowList[0]?.roleIds}
        /> */}
      </>
    )
  }
}
